// lib/redis-client.ts
import Redis from 'ioredis';

// 创建客户端类（不带泛型！只做连接管理）
class RedisConnection {
  private client: Redis;

  constructor() {
    this.client = new Redis({
      host: process.env.REDIS_HOST || '127.0.0.1',
      port: parseInt(process.env.REDIS_PORT || '6379'),
      password: process.env.REDIS_PASSWORD || '123456',
      db: parseInt(process.env.REDIS_DB || '0'),
      maxRetriesPerRequest: 3,
      retryStrategy: (times) => Math.min(times * 50, 2000),
    });

    this.client.on('error', (err) => {
      console.error('[Redis] 连接错误:', err);
    });

    this.client.on('connect', () => {
      console.log('[Redis] 已连接');
    });
  }

  getClient(): Redis {
    return this.client;
  }

  async disconnect(): Promise<void> {
    await this.client.quit();
  }
}

// 👇 单例模式：防止热重载时多次创建连接
const globalWithRedis = global as unknown as {
  __redisConnection?: RedisConnection;
};

let redisConnection: RedisConnection;

if (process.env.NODE_ENV === 'production') {
  redisConnection = new RedisConnection();
} else {
  // 开发环境使用全局变量避免 HMR 重复创建
  if (!globalWithRedis.__redisConnection) {
    globalWithRedis.__redisConnection = new RedisConnection();
  }
  redisConnection = globalWithRedis.__redisConnection;
}

export default redisConnection;
